<?php
if (!defined('APP_ID')) { die('No direct script access allowed'); }

/**
 * View class
 */
class View {
	private $_file = '';
	private $_data = array();

	public static function factory($file, $data = array()) {
		return new View($file, $data);
	}

	private function __construct($file, $data = array()) {
		// Finding view file
		$file_path = Node::findFile('views', $file);
		if (!$file_path) {
			throw new Node_Exception('View not found');
		}
		$this->_file = $file_path;
		$this->_data = $data + $this->_data;
	}

	public function set($key, $value) {
		$this->_data[$key] = $value;
		return $this;
	}

	public function get($key, $default = null) {
		$result = $default;
		if (isset($this->_data[$key])) {
			$result = $this->_data[$key];
		}
		return $result;
	}

	public function render() {
		// Extracting variables
		extract($this->_data);
		ob_start();

		try {
			include($this->_file);
		} catch (Exception $e) {
			ob_end_clean();
			throw new Node_Exception('Error rendering view');
		}

		return ob_get_clean();
	}

	public function __set($key, $value) {
		$this->set($key, $value);
	}

	public function __get($key) {
		return $this->get($key);
	}

	public function __toString() {
		return $this->render();
	}
}
